#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>

#define SIGN " "
#define SIZE 1024
char arr[SIZE];
char* cutting_arr[SIZE];

const char* gethome()
{
    char* str = getenv("HOME");
    if(!str)
    {
        return NULL;
    }
    return str;
}

const char* getuser()
{
    char* str = getenv("USER");
    if(!str)
    {
        return NULL;
    }
    return str;
}

const char* getpwd()
{
    char* str = getenv("PWD");
    if(!str)
    {
        return NULL;
    }
    return str;
}

const char* getsauthority()
{
    char* str = ":~$ ";
    if(strcmp(getuser(),"root") == 0)
    {
        return ":~# ";
    }

    if(!str)
    {
        return NULL;
    }
    return str;
}

int interaction(char* _arr, int size)
{
    printf("[%s@%s]%s",getuser(),getpwd(),getsauthority());
    fgets(_arr, size ,stdin);
    arr[strlen(_arr) - 1] = '\0';
    return 0;
}

void cuttingstr(char* _arr, const int size)
{
    char temp_arr[size];
    strcpy(temp_arr,_arr);

    int i = 0;
    cutting_arr[i++] = strtok(temp_arr,SIGN);
    while(cutting_arr[i++] = strtok(NULL,SIGN));
    for(int i = 0; cutting_arr[i];i++)
    {
        printf("%s\n",cutting_arr[i]);
    }
}

//解析指令
void resolve_instruct()
{
    //判断内建命令
    if((cutting_arr[0] == "cd") == 0)
    {
        char* temp = cutting_arr[1];
        if(strcmp(temp,"cd"))//空，去家目录
        {
            chdir(gethome());
        }
        else//非空
        {
            chdir(temp);
        }
        return;
    }

    pid_t id = fork();
    if(id == 0)//子进程
    {
        int ret = execvp(cutting_arr[0],cutting_arr);
        if(ret == -1)
        {
            perror("exec error:");
        }
        exit(1);
    }

    //父进程
    //printf("I am father\n");
    int status = 0;
    waitpid(id, &status, 0);

    //if(!WIFSIGNALED(status))
    //{
    //    printf("%d\n",WEXITSTATUS(status));
    //}
}

int main(int argc, char* argv[])
{
    while(1)
    {
    //1 设计交互式页面
    interaction(arr,SIZE);

    //2 分割字符串
    cuttingstr(arr,SIZE);

    //3,解析指令
    resolve_instruct();  
    }
    return 0;
}